package viv.karaoke.book;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class favoriteDataSource {
	
	// Database fields
	private SQLiteDatabase database;
	private mySQLiteHelper dbHelper;
	
	private String[] favoriteColumns = {
				 mySQLiteHelper.FAVORITE_ID,
				 mySQLiteHelper.FAVORITE_USER_ID,
				 mySQLiteHelper.FAVORITE_SONG_ID
				 };

	public favoriteDataSource(Context context) {
	dbHelper = new mySQLiteHelper(context);
	}
	
	public void open() throws SQLException {
	database = dbHelper.getWritableDatabase();
	}
	
	public void close() {
	dbHelper.close();
	}
	
	public favorite createFavorite(long userId, long songId) {
		ContentValues values = new ContentValues();
		
		values.put(mySQLiteHelper.FAVORITE_USER_ID, userId);
		values.put(mySQLiteHelper.FAVORITE_SONG_ID, songId);		
			    
		long insertId = database.insert(mySQLiteHelper.TABLE_FAVORITE, null,values);
			    
		Cursor cursor = database.query(mySQLiteHelper.TABLE_FAVORITE, favoriteColumns, mySQLiteHelper.FAVORITE_ID + " = " + insertId, null, null, null, null);
	
		favorite newfavorite = new favorite();
		try{
			cursor.moveToFirst();
			newfavorite = cursorToFavorite(cursor);
		}
		catch(Exception ex)
		{
		}
		finally
		{
			//Make sure to close the cursor
			cursor.close();
		}
		
	    return newfavorite;
	}
	
	public void deleteFavorite(favorite favorite) {
		    long id = favorite.getFavoriteId();
		    System.out.println("Favorite deleted with id: " + id);
		    database.delete(mySQLiteHelper.TABLE_FAVORITE, mySQLiteHelper.FAVORITE_ID
		        + " = " + id, null);
	}

	private favorite cursorToFavorite(Cursor cursor) {
		favorite favorite = new favorite();
		
		favorite.setFavoriteId(cursor.getLong(0));
		favorite.setUserId(cursor.getLong(1));
		favorite.setSongId(cursor.getLong(2));
	    
	    return favorite;
	  }	
}